package com.example.servlet;

import cn.hutool.json.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@WebServlet(name = "demo01", value = "/demo01")
public class ServletDemo01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        String type = req.getParameter("type");
        System.out.println(type);
        switch (type) {
            case "1":
                doCase1(req, resp);
                break;
            case "2":
                doCase2(req, resp);
                break;
            case "3":
                doCase3(req, resp);
                break;
            case "4":
                doCase4(req, resp);
                break;
            case "5":
                doCase5(req, resp);
                break;
            case "6":
                doCase6(req, resp);
                break;
            case "7":
                doCase7(req, resp);
                break;
            case "8":
                doCase8(req, resp);
                break;
            default:
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "没有提供type");
                break;
        }
    }

    /* 响应网页文本内容 */
    private void doCase1(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        /*resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");*/
        // 等同于
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<p>你好</p>"); // 进body
        writer.close();
    }

    /* 响应一个服务端网页->jsp */
    private void doCase2(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        // 为请求添加参数、属性
        req.setAttribute("name", "kunkun");
        req.setAttribute("age", 18);
        // 请求转发，jsp是一个还未转换的servlet
        // 不会修改url地址
        // 可以转发给servlet和jsp
        req.getRequestDispatcher("demo01.jsp")
                .forward(req, resp);
    }

    /* 重定向到其他资源 */
    private void doCase3(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        // 响应重定向：相当于我回复你，你去找XXX
//        resp.sendRedirect("demo01.jsp");
        resp.sendRedirect("hello-servlet");
    }

    /* 响应JSON文本 */
    private void doCase4(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        /* 设置响应的数据格式 */
        /* 设置了application/json之后，浏览器会帮你解析JSON */
        resp.setContentType("application/json;charset=utf-8");
        /*resp.setContentType("text/plain");
        resp.setCharacterEncoding("utf-8");*/
        PrintWriter writer = resp.getWriter();
        /*String json = "{\n" +
                "  \"name\": \"张三\",\n" +
                "  \"age\": 20,\n" +
                "  \"sex\": \"男\",\n" +
                "  \"grade\": {\n" +
                "    \"number\": 20224128,\n" +
                "    \"major\": \"软件开发\"\n" +
                "  },\n" +
                "  \"hobby\": [\n" +
                "    \"编程\",\n" +
                "    \"游泳\",\n" +
                "    \"爬树\"\n" +
                "  ]\n" +
                "}";*/
        /* 先构建Java对象，使用工具转换成JSON文本 */
        Map<String, Object> data = new HashMap<>();
        data.put("name", "kunkun");
        data.put("age", 18);
        data.put("sex", "男");
        Map<String, Object> grade = new HashMap<>();
        grade.put("number", 20224128);
        grade.put("major", "软件开发");
        data.put("grade", grade);
        List<String> hobbies = new ArrayList<>();
        Collections.addAll(hobbies, "编程", "游泳", "爬树");
        data.put("hobby", hobbies);
        /* 借助hutool转换Java对象成JSON */
        String json = JSONUtil.toJsonStr(data);
        writer.write(json); // JSON字符串
        writer.close();
    }

    /* 获取网络图片 */
    private void doCase5(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        // image/xxx，根据图片真实的后缀来定
        resp.setContentType("image/jpeg");
        // 读取某一张图片
        InputStream is = new FileInputStream("F:/课堂/Java Web程序设计/孙悟空.jpg");
        // 将图片的字节数据通过输出流往客户端输出
        // 响应输出流
        ServletOutputStream os = resp.getOutputStream();
        // 小文件可以以最大字节数去读
        byte[] b = new byte[is.available()]; // 最大字节数
        is.read(b);
        os.write(b);
        os.flush();
        os.close();
        is.close();
    }

    /* 响应一个网络音频 */
    private void doCase6(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        // audio/mpeg
        resp.setContentType("audio/mpeg");
        // 读取某一段音频
        InputStream is = new FileInputStream("F:/课堂/Java Web程序设计/Uu-夏天的风.mp3");
        // 将音频的字节数据通过输出流往客户端输出
        // 响应输出流
        ServletOutputStream os = resp.getOutputStream();
        // 音频/视频文件不要以最大字节数去读
        byte[] b = new byte[1024 * 100]; // 100K
        int len = 0;
        while ((len = is.read(b)) != -1) {
            os.write(b, 0, len);
        }
        os.flush();
        os.close();
        is.close();
    }

    /* 响应一个网络视频 */
    private void doCase7(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        // video/mp4
        resp.setContentType("video/mp4");
        // 读取某一段视频
        InputStream is = new FileInputStream("F:/课堂/Java Web程序设计/抖音广告.mp4");
        // 将视频的字节数据通过输出流往客户端输出
        // 响应输出流
        ServletOutputStream os = resp.getOutputStream();
        // 音频/视频文件不要以最大字节数去读
        byte[] b = new byte[1024 * 100]; // 100K
        int len = 0;
        while ((len = is.read(b)) != -1) {
            os.write(b, 0, len);
        }
        os.flush();
        os.close();
        is.close();
    }

    /* 下载一个文件 */
    private void doCase8(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        // 下载需要指定响应头Content-Disposition
        resp.setHeader("Content-Disposition",
                "attachment; filename=" +
                        URLEncoder.encode("apache-maven-3.9.6-bin.zip",
                                StandardCharsets.UTF_8));
        InputStream is = new FileInputStream("F:/课堂/Java Web程序设计/apache-maven-3.9.6-bin.zip");
        ServletOutputStream os = resp.getOutputStream();
        byte[] b = new byte[1024 * 100]; // 100K
        int len = 0;
        while ((len = is.read(b)) != -1) {
            os.write(b, 0, len);
        }
        os.flush();
        os.close();
        is.close();
    }
}